import React, {Component} from 'react'
import {
    DeviceEventEmitter,
    Dimensions,
    FlatList,
    Image,
    RefreshControl,
    ScrollView,
    Text,
    TouchableOpacity,
    View
} from 'react-native'
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from "../../../res/language/i18n";
import AlertDialog from "../../../custom/AlertDialog";
import ViewUtils from "../../../utils/ViewUtils";


export default class AutoOrderPage extends Component {


    // 构造
    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        // 初始状态
        this.state = {
            goodsData: [],
            isLoading: false,
            alertVisible: false,
            selectGoods: -1,
        };
    }


    componentDidMount() {
        this.getAutoOrders();
    }


    /**
     * 获取数据
     * */
    getAutoOrders() {
        this.setState({
            isLoading: true,
        });
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getAutoOrderData?',
            'user_id=' + this.props.user_id)
            .then((result) => {
                let data = result.data;
                if (result.code === 200 && data) {
                    this.setState({
                        goodsData: data.user_auto_order_goods,
                        isLoading: false,
                    })
                } else {
                    this.setState({
                        isLoading: false,
                    })
                }
            })
            .catch((error) => {
                this.setState({
                    isLoading: false,
                });
                console.log('AutoOrderPage--getAutoOrders--error:' + error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })

    }


    /**
     * 删除自动订单
     */
    deleteAutoOrder() {
        this.setState({
            alertVisible: false,
            isLoading: true,
        });

        let state = this.state;
        let selectGoods = state.selectGoods;
        let _goodsData = state.goodsData[selectGoods];

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'deleteAutoOrderGoods?',
            'rec_id=' + _goodsData.rec_id)
            .then((result) => {
                if (result.code === 200) {
                    let newGoods = state.goodsData;
                    newGoods.splice(selectGoods, 1);
                    this.setState({
                        goodsData: newGoods,
                        isLoading: false,
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));

                    this.setState({
                        isLoading: false,
                    });
                }
            })
            .catch((error) => {
                this.setState({
                    isLoading: false,
                });
                console.log('AutoOrderPage--getAutoOrders--error:' + error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });


    }


    /**
     * 编辑产品数量
     */
    updateGoodsNumber(productInfo, isAdd, index) {


        let _goods_number = productInfo.goods_number;

        if (isAdd) {
            _goods_number++
        } else {
            if (_goods_number > 0) {
                _goods_number--
            } else {
                return
            }
        }

        this.setState({
            isLoading: true,
        });

        let formData = new FormData();
        formData.append('user_id', this.props.user_id);
        formData.append('main_user_id', this.props.main_user_id);
        formData.append('goods_id', productInfo.goods_id);
        formData.append('product_id', productInfo.product_id);
        formData.append('goods_number', _goods_number);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'saveAutoOrders', formData)
            .then((result) => {

                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    let _goodsData = this.state.goodsData;
                    _goodsData[index].goods_number = _goods_number;
                    this.setState({
                        isLoading: false,
                        goodsData: _goodsData,
                    });
                } else {
                    this.setState({
                        isLoading: false,
                    });
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.setState({
                    isLoading: false,
                });
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('AutoOrderPage--updateGoodsNumber-error: ', error)
            })
    }


    /**
     * init flatList item
     * */
    renderGoodsItem(item, index) {
        let product = item.product;
        let goodsName = '';
        if (product) {
            goodsName = product.goods_local_name;
            if (this.state.country === 'CN') {
                if (I18n.locale === 'uy') {
                    goodsName = product.goods_name;
                }
            } else {
                if (I18n.locale === 'ru') {
                    goodsName = product.goods_name;
                }
            }
        }

        return <TouchableOpacity
            key={index}
            style={[StyleUtils.justifySpace, {
                alignItems: null,
                padding: 16,
                paddingTop: 0,
                paddingRight: 0,
            }]}>

            <Image
                style={{width: 100, height: 100}}
                source={{uri: IMAGE_URL + product.image}}/>

            <View style={{flex: 1, padding: 8, justifyContent: 'space-between',}}>
                <Text
                    style={[{fontSize: 16},StyleUtils.smallFont]}
                    numberOfLines={2}
                >{goodsName}</Text>


                <Text
                    style={[{fontSize: 16, color: 'red'},StyleUtils.smallFont]}
                    numberOfLines={2}
                >{(product.goods_pv || 0).toFixed(2)} PV</Text>


                <View style={StyleUtils.justifySpace}>


                    <Text
                        style={[{fontSize: 14, color: 'gray'},StyleUtils.smallFont]}
                        numberOfLines={2}
                    >{(item.add_time || '            ').substring(0, 11)}</Text>

                    {/**render goods number*/}
                    <View
                        style={[StyleUtils.justifySpace, {
                            borderWidth: 1,
                            width: 100,
                            height: 26,
                            borderColor: '#e3e3e3',
                        }]}>
                        <TouchableOpacity
                            onPress={() => {
                                this.updateGoodsNumber(item, false, index)
                            }}
                            style={[{
                                width: 26,
                                height: 26,
                            }, StyleUtils.center]}>
                            <Image
                                resizeMode='cover'
                                style={{
                                    width: 8,
                                    height: 8,
                                    tintColor: '#a3a3a3',
                                    resizeMode: 'cover',
                                }}
                                source={require('../../../res/images/ic_reduce.png')}
                            />
                        </TouchableOpacity>
                        <Text
                            numberOfLines={1}
                            style={[{fontSize: 14, width: 44, textAlign: 'center'},StyleUtils.smallFont]}>
                            {item.goods_number}
                        </Text>
                        <TouchableOpacity
                            onPress={() => {
                                this.updateGoodsNumber(item, true, index)
                            }}
                            style={[{
                                width: 26,
                                height: 26,
                            }, StyleUtils.center]}>
                            <Image
                                resizeMode="cover"
                                style={{
                                    width: 8,
                                    height: 8,
                                    tintColor: '#a3a3a3',
                                    resizeMode: 'cover',
                                }}
                                source={require('../../../res/images/ic_add.png')}/>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>

            <TouchableOpacity
                onPress={() => {
                    this.setState({
                        alertVisible: true,
                        selectGoods: index,
                    })
                }}
                style={[{width: 50, height: 50}, StyleUtils.center]}>
                <Image
                    style={{width: 16, height: 16}}
                    source={require('../../../res/images/ic_close.png')}/>
            </TouchableOpacity>
        </TouchableOpacity>
    }

    render() {
        let state = this.state;
        return (<View style={StyleUtils.flex}>
            <Navigation onClickLeftBtn={() => this.props.navigator.pop()}/>


            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={state.isLoading}
                        onRefresh={() => {
                        }}
                    />
                }>


                {ViewUtils.getTitleView(I18n.t('o.standingOrder'), I18n.t('o.autoOrderContent'))}
                {state.goodsData && state.goodsData.length > 0 ? <FlatList
                        extraData={this.state}
                        renderItem={(item) => this.renderGoodsItem(item.item, item.index)}
                        data={state.goodsData}/>
                    :
                    <View
                        style={[StyleUtils.center, {
                            marginTop: 60,
                            padding: 16
                        }]}>
                        <Text style={StyleUtils.smallFont}>{I18n.t('default.noData')}</Text>
                        {ViewUtils.getButton('set auto order', () => {
                            this.props.navigator.popToTop();
                            DeviceEventEmitter.emit('goToPage', 0)
                        }, {marginTop: 50})}
                    </View>}

            </ScrollView>

            <AlertDialog
                leftBtnOnclick={() => {

                    this.deleteAutoOrder()
                }}
                contentTv={I18n.t('default.delete')}
                visible={state.alertVisible}
                requestClose={() => {
                    this.setState({
                        alertVisible: false
                    })
                }}/>

        </View>)
    }

}